<template>
  <PageContainer>
    <Header :title="pageTitle">
      <view class="hb-h-9 hb-box-content hb-py-2 hb-px-4">
        <TSearch text="搜索" @confirm="handleConfirm"></TSearch>
      </view>
    </Header>
    <view>
      <view class="hb-p-4 hb-pb-0">
        <TmCheckboxGroup v-model="selected">
          <template v-for="item in dataList" :key="item.id">
            <view class="hb-w-full">
              <MemberItem :item="item" @click="handleSelectItem(item)">
                <TmCheckbox
                  :margin="[0, 0, 24, 0]"
                  :size="40"
                  :disabled="item.isActivate === 0 || disabled.includes(item.id)"
                  :value="item.id"
                />
              </MemberItem>
            </view>
          </template>
        </TmCheckboxGroup>
        <Empty v-if="dataList.length === 0" />
      </view>
      <BottomSubmit :submit-btn-label="submitBtnLabel" @submit="handleSelectSubmit" />
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* selectMembers 选择成员 */
  import { selectCircleMemberList } from '@/api/contact';
  import { CircleMemberListResult } from '@/api/contact/types';
  import { SelectMembers } from '@/router/types/modules';
  import { difference, isArray } from 'lodash-es';
  import MemberItem from '../components/MemberItem.vue';

  const dataList = ref<CircleMemberListResult[]>([]);
  const circlesId = ref<number>(0);
  const pageTitle = ref<string>('选择成员');
  const btnText = ref<string>('确认选择');

  const getDataList = (keyWord?: string) => {
    selectCircleMemberList({ id: circlesId.value, keyWord }).then((res) => {
      dataList.value = res;
    });
  };

  let success: SelectMembers['success'];
  const selected = ref<number[]>([]);
  const disabled = ref<number[]>([]);
  customOnload<'selectMembers'>((op) => {
    circlesId.value = op.id;
    if (op.type === 'admin') {
      pageTitle.value = '添加管理员';
      btnText.value = '添加为管理员';
    }

    if (isArray(op.selected) && op.selected.length > 0) {
      if (op.type === 'admin') {
        disabled.value = [...op.selected];
      }
      selected.value = [...op.selected];
    }

    getDataList();
    success = op.success;
  });

  const handleSelectItem = (v: CircleMemberListResult) => {
    if (disabled.value.includes(v.id)) return;
    if (selected.value.includes(v.id)) {
      selected.value = selected.value.filter((item) => item !== v.id);
    } else {
      selected.value.push(v.id);
    }
  };

  /** 搜索 */
  const handleConfirm = (val: string) => {
    getDataList(val);
  };

  const ids = computed(() => difference(selected.value, disabled.value));

  const submitBtnLabel = computed(() => `${btnText.value}（${ids.value.length}）`);

  const handleSelectSubmit = () => {
    success?.(dataList.value.filter((item) => ids.value.includes(item.id)));
    navigateBack();
  };
</script>

<style lang="scss" scoped></style>
